package com.delong.spring.handler;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Hex;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.delong.util.AliYunOSSUtil;
import com.delong.util.ReadApkUtil;
import com.delong.util.ReadFileCrc32Util;

/**
 * file upload component
 * 
 * @author liyang
 *
 */
@Controller
public class FileUpLoadController {

	Logger log = Logger.getLogger(FileUpLoadController.class);

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public @ResponseBody String handleFileUpload(@RequestParam("file") MultipartFile file, ServletRequest req,
			@RequestParam("flag") int flag) {

		if (!file.isEmpty()) {
			try {

				String key = "";
				JSONObject result = new JSONObject();
				if (file.getContentType().equals("image/png") || file.getContentType().equals("image/jpg")
						|| file.getContentType().equals("image/jpeg")) {
					byte[] bytes = file.getBytes();
					String filename = file.getOriginalFilename();
					String filePostfix = filename.substring(filename.lastIndexOf(".") + 1);
					BufferedImage image = ImageIO.read(file.getInputStream());
					Integer width = image.getWidth();
					Integer height = image.getHeight();
					BufferedImage thumbnail = null;
					if (flag == 1 && width > height) {
						int type = image.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : image.getType();
						thumbnail = this.resizeImage(image, type, height, width);
						ByteArrayOutputStream baos = new ByteArrayOutputStream();
						ImageIO.write(thumbnail, filePostfix, baos);
						bytes = baos.toByteArray();
					}

					key = java.util.UUID.randomUUID().toString() + "." + filePostfix;
					String filepath = AliYunOSSUtil.applyOSS(key, bytes, file.getContentType());
					System.out.println(file.getContentType());
					result.put("code", 0);
					result.put("filepath", filepath);
				} else {
					result.put("code", 1);
					result.put("msg", "类型错误");
				}
				HttpServletRequest request = (HttpServletRequest) req;
				log.info(request.getSession().getAttribute("username") + "上传图片文件" + key);
				return result.toJSONString();

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else {
			return "";
		}
		return null;
	}

	@RequestMapping(value = "/uploadapk", method = RequestMethod.POST)
	public @ResponseBody String getApkInfo(@RequestParam("file") MultipartFile file, ServletRequest req) {

		if (!file.isEmpty()) {
			try {
				byte[] bytes = file.getBytes();
				String filename = file.getOriginalFilename();
				String key = java.util.UUID.randomUUID().toString() + "."
						+ filename.substring(filename.lastIndexOf(".") + 1);
				String destinationPath = "src/main/resources/static/uploadfile/apkfile/" + key;
				saveFile(file, destinationPath);
				String filepath = AliYunOSSUtil.applyOSS(key, bytes, file.getContentType());
				JSONObject result = new JSONObject();
				Map<String, String> ApkInfo = ReadApkUtil.getApkMessage(destinationPath);
				if (ApkInfo != null) {
					String packageName = ApkInfo.get("packageName");
					result.put("code", 0);
					result.put("filepath", filepath);
					result.put("packageName", packageName);
					result.put("appVersion", ApkInfo.get("appVersion"));
					result.put("appVersionCode", ApkInfo.get("appVersionCode"));
					result.put("appbyte", bytes.length);
					// System.out.println("########");
					Long crc32 = ReadFileCrc32Util.readCrc32FromBytes(file.getBytes());
					result.put("crc32", Long.toHexString(crc32));
					MessageDigest md = MessageDigest.getInstance("MD5");
					byte[] thedigest = md.digest(file.getBytes());
					String md5 = new String(Hex.encodeHex(thedigest));
					result.put("md5", md5);
					// System.out.println();
				} else {
					result.put("code", 1);
					result.put("msg", "类型错误，或者文件不完整");
				}
				HttpServletRequest request = (HttpServletRequest) req;
				log.info(request.getSession().getAttribute("username") + "上传APK文件" + key);
				// upload file to aliyun right now write this splice code
				return result.toJSONString();
			} catch (Exception e) {
				return "You failed to upload error " + e.getMessage();
			}
		} else {
			return "";
		}
	}

	/**
	 * 存储上传文件信息
	 * 
	 * @param file
	 *            文件内容
	 * @param distintionPath
	 *            存储路径
	 * @param postfix
	 *            文件后缀
	 * @return
	 */
	private void saveFile(MultipartFile file, String distintionPath) {

		try {
			byte[] bytes = file.getBytes();
			// String filename = file.getOriginalFilename();
			String path = distintionPath;
			BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(path)));
			stream.write(bytes);
			stream.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private BufferedImage resizeImage(BufferedImage originalImage, int type, int IMG_WIDTH, int IMG_HEIGHT) {
		BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
		Graphics2D g = resizedImage.createGraphics();
		g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
		g.dispose();

		return resizedImage;
	}

}
